package com.issoft.studentresitor.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.issoft.studentresitor.domain.pojo.Dorm;
import com.issoft.studentresitor.domain.pojo.Student;
import com.issoft.studentresitor.domain.query.DormQuery;
import com.issoft.studentresitor.domain.vo.DormVo;
import com.issoft.studentresitor.mapper.DormMapper;
import com.issoft.studentresitor.mapper.StudentMapper;
import com.issoft.studentresitor.service.IDormService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.issoft.studentresitor.utils.PageResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author GJH
 * @since 2025-09-14
 */
@Slf4j
@Service
public class DormServiceImpl extends ServiceImpl<DormMapper, Dorm> implements IDormService {
    @Autowired
    private DormMapper dormMapper;
    @Autowired
    private StudentMapper studentMapper;

    @Override
    public DormVo countDrom() {
        return dormMapper.countDrom();
    }

    @Override
    public PageResult<DormVo> queryDormPage(DormQuery query) {
        PageHelper.startPage(query.getPage(), query.getPageSize());
        List<DormVo> dormVos = dormMapper.queryDormPage(query);
        Page<DormVo> pageResult =(Page<DormVo>) dormVos;
        return new PageResult<>(pageResult.getTotal(), pageResult.getResult());
    }


    /**
     * 查询宿舍信息
     * @param userId
     * @return
     */
    @Override
    public Dorm queryDormInfo(Integer userId) {
        return dormMapper.queryDormInfo(userId);
    }

    @Override
    @Transactional
    public boolean selectDorm(Integer userId, Integer dormId) {
        // 通过userId给student表设置宿舍id
        UpdateWrapper<Student> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("user_id", userId)
                .set("dorm_id", dormId);
        boolean update = studentMapper.update(null, updateWrapper) > 0;

        // 通过dormId给dorm表设置当前入住人数
        // 直接通过dorm_id查询宿舍信息
        Dorm dormInfo = dormMapper.selectByDormId(dormId);
        if (dormInfo == null) {
            log.error("未找到ID为{}的宿舍信息", dormId);
            return false;
        }

        // 检查宿舍是否已满
        if (dormInfo.getCurrentOccupancy() >= dormInfo.getCapacity()) {
            log.warn("宿舍ID为{}已满，无法选择", dormId);
            return false;
        }

        UpdateWrapper<Dorm> updateWrapper1 = new UpdateWrapper<>();
        updateWrapper1.eq("dorm_id", dormId)
                .set("current_occupancy", dormInfo.getCurrentOccupancy() + 1);
        boolean update1 = dormMapper.update(null, updateWrapper1) > 0;

        return update && update1;
    }
}
